// pages/goodsdetail/index.js
import {
  GoodsDetailRequest
} from "../../api/goodsdetial.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { goods_id } = options
    this.request(goods_id)
  },
  Goods: {},
  //请求商品
  request(goods_id) {
    GoodsDetailRequest({
      url: "/goods/detail",
      data: {
        goods_id
      }
    }).then(res => {
      this.Goods = res.data.message
      this.setData({
        goods: {
          id: res.data.message.goods_id,
          pics: res.data.message.pics,
          name: res.data.message.goods_name,
          introduce: res.data.message.goods_introduce,
          price: res.data.message.goods_price
        }
      })
    })
  },

  // 添加到购物车
  AddCart() {
    // 读取本地的购物车数组
    const goodslist = wx.getStorageSync("goodslist") || [];
    const index = goodslist.findIndex(item => {
      return item.goods_id == this.Goods.goods_id
    })
    if (index == -1) {
      // 不存在时
      this.Goods.count = 1
      this.Goods.checked = true
      goodslist.push(this.Goods)
    } else {
      goodslist[index].count++
    }
    // 将购物车数组存储到本地
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      mask: true,
    });

    wx.setStorageSync("goodslist", goodslist);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})